package com.whale.springsession.config;

import com.whale.springsession.filter.MyFilter;
import com.whale.springsession.service.MyAccessDeniedHandler;
import com.whale.springsession.service.MyAuthenticationEntryPoint;
import com.whale.springsession.service.MyAuthenticationFailureHandler;
import com.whale.springsession.service.MyAuthenticationSuccessHandler;
import com.whale.springsession.service.UcFormLoginAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.session.SessionManagementFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter implements Ordered {

    @Autowired
    UcFormLoginAuthenticationProvider ucFormLoginAuthenticationProvider;

    /**
     * 在springsecurity5 之后，使用密码的时候，必须加密，所有必须在spring里注入加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(ucFormLoginAuthenticationProvider);
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     *
     * Security默认的configure是有一套配置的，如果我们重写了之后，会发生接口不受到保护了，是因为你重写了父类
     * 需要自己在这里配置下.anyRequest().authenticated()
     *
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
                .requestMatchers().antMatchers("/login", "/logout", "/con1", "/con2").and()
                .formLogin()
                .successHandler(new MyAuthenticationSuccessHandler()).failureHandler(new MyAuthenticationFailureHandler())
                .and().logout().logoutSuccessUrl("http://www.baidu.com")
                .and().exceptionHandling().accessDeniedHandler(new MyAccessDeniedHandler())
                .authenticationEntryPoint(new MyAuthenticationEntryPoint())
                .and()
                .authorizeRequests()
                .antMatchers("/con2").permitAll()
                .anyRequest().authenticated()
        ;

        httpSecurity.addFilterBefore(new MyFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public int getOrder() {
        return 101;
    }
}
